//
//  GoodsAttribute.swift
//  ReactNativeIOS
//
//  Created by FishWithoutWings on 2017/12/16.
//  Copyright © 2017年 chenliang. All rights reserved.
//

import RealmSwift

class GoodsAttribute: Object {
    
    @objc dynamic var attrId = 0
    @objc dynamic var attrName = ""
    @objc dynamic var sort = 0
    @objc dynamic var isMain = 0
    @objc dynamic var isNormal = 0
    @objc dynamic var isMust = 0
    @objc dynamic var isDefault = 0
    @objc dynamic var sortNo = 0
    @objc dynamic var inputType = ""
    @objc dynamic var dicId = 0
    @objc dynamic var valueType = 0
    @objc dynamic var categoryId = 0
    
    override class func primaryKey() -> String? {
        return "attrId"
    }
    
    class func create(_ goodsAttributes: [Any], isAsync: Bool = true) {
        let closure = {
            let realm = YYRealm.initialize()
            
            realm.beginWrite()
            realm.delete(realm.objects(self))
            for goodsAttribute in goodsAttributes {
                realm.create(self, value: goodsAttribute, update: true)
            }
            try! realm.commitWrite()
        }
        
        if isAsync {
            YYRealm.async(closure)
        } else {
            closure()
        }
    }
    
    class func getOne(attrId: Int) -> GoodsAttribute? {
        let realm = YYRealm.initialize()
        let items = realm.objects(self).filter("attrId = \(attrId)")
        if items.count > 0 {
            return items[0]
        } else {
            return nil
        }
    }

}
